<template>
	<div class="edit-popup">
		<popup ref="popupRef" :title="popupTitle" :async="true" width="550px" :clickModalClose="true"
			@confirm="handleSubmit" @close="handleClose">
			<el-table :class="className" :data="options.tableTile" resizable border size="small" row-key="id">
				<el-table-column label="序号" width="60" align="center" type="index"></el-table-column>
				<el-table-column label="列名" prop="name"></el-table-column>
				<el-table-column label="显示/隐藏" width="120" fixed="right">
					<template #default="{ row }">
						<el-switch v-model="row.display" :active-value="1" :inactive-value="0" />
					</template>
				</el-table-column>
			</el-table>
		</popup>
	</div>
</template>
<script lang="ts" setup>
	import type {
		FormInstance
	} from 'element-plus'
	import Popup from '@/components/popup/index.vue'
	import Sortable from 'sortablejs'
	import {
		getCommonFieldDisplay,
		setCommonFieldDisplay
	} from '@/api/tools/code'
	const emit = defineEmits(['success', 'close'])
	const props = defineProps({
		type: {
			type: String,
			default: ''
		},
		className: {
			type: String,
			default: 'className'
		},
	})
	// const props = defineProps(['type','className'])
	const formRef = shallowRef < FormInstance > ()
	const popupRef = shallowRef < InstanceType < typeof Popup >> ()
	const mode = ref('add')
	const popupTitle = computed(() => {
		return mode.value == 'edit' ? '表单设置' : '表单设置'
	})
	const formData = reactive({})
	const options = reactive({
		tableTile: [] as any[]
	})
	const getOptions = () => {
		getCommonFieldDisplay({
			type: props.type
		}).then((data: any) => {
			options.tableTile = data
			initSort(props.className)
		})
	}
	const handleSubmit = async () => {
		formData[props.type] = JSON.stringify(options.tableTile)
		await formRef.value?.validate()
		mode.value == 'edit' ? await setCommonFieldDisplay(formData) : await setCommonFieldDisplay(formData)
		popupRef.value?.close()
		emit('success')
	}
	const open = (type = 'add') => {
		mode.value = type
		popupRef.value?.open()
	}
	const handleClose = () => {
		emit('close')
	}
	const initSort = (className: any) => {
		const table = document.querySelector(`.${  className  } .el-table__body-wrapper tbody`)
		Sortable.create(table, {
			group: 'shared',
			draggable: ".el-table__row",
			animation: 150,
			easing: 'cubic-bezier(1, 0, 0, 1)',
			onStart: () => {
				// console.log("开始拖动");
			},
			// 结束拖动事件
			onEnd: ({
				newIndex,
				oldIndex
			}: any) => {
			
				setNodeSort(options.tableTile, oldIndex, newIndex)
			},
		})
	}
	// 拖拽完成修改数据排序
	const setNodeSort = (data: any, oldIndex: any, newIndex: any) => {
		const currRow = data.splice(oldIndex, 1)[0];
		data.splice(newIndex, 0, currRow);
	}
	getOptions()
	defineExpose({
		open
	})
</script>
